//
//  WSMainController.swift
//  微博
//
//  Created by 武莎莎 on 15/9/6.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

class WSMainController: UITabBarController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.addChildViewControllers()
        
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        self.setUpPlusBtn()
    }
    
    // 添加子控制器
    private func addChildViewControllers() {
        self.addChildViewController(WSHomeController(), title: "首页", imageName: "tabbar_home")
        self .addChildViewController(WSMessageController(), title: "消息", imageName: "tabbar_message_center")
        // 添加一个空白的占位
        self.addChildViewController(UIViewController())
        
        self.addChildViewController(WSDiscoverController(), title: "发现", imageName: "tabbar_discover")
        self.addChildViewController(WSProfileController(), title: "我", imageName: "tabbar_profile")
    }
    
    // 添加带有主控制器的navigationController
    private func addChildViewController(vc:UIViewController, title:String, imageName:String) {
        
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }
    
    // MARK - 中间的加号
    private lazy var plusBtn:UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState:
            UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        self.tabBar.addSubview(btn)
        
        btn.addTarget(self, action: "clickedPlusBtn", forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
        }()
    
    // MARK:加上按钮的点击事件
    @objc private func clickedPlusBtn(){
        
//        NSNotificationCenter.defaultCenter().postNotificationName(WSSwitchRootViewControllerNotification, object: nil)
        
        let vc = WSComposeController()
        let nav = UINavigationController(rootViewController: vc)
        presentViewController(nav, animated: true) { () -> Void in
            
        }
    }
    // 设置加号按钮显示的位置
    private func setUpPlusBtn(){
        
        let count = childViewControllers.count
        let w = tabBar.bounds.width / CGFloat(count)
        
        plusBtn.frame = CGRectMake(2*w, 0, w, tabBar.bounds.height)
        
    }
}
